<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="onBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="title">分类管理</text>
      <view class="add-btn" @click="showAddCategoryModal">添加</view>
    </view>

    <!-- 分类列表 -->
    <view class="category-list">
      <view 
        v-for="(category, index) in categories" 
        :key="category.id"
        class="category-item"
        :class="{ active: selectedCategoryId === category.id }"
        @click="selectCategory(category.id)"
        @longpress="showCategoryActions(category)"
      >
        <view class="category-color" :style="{ backgroundColor: category.color }"></view>
        <view class="category-info">
          <text class="category-name">{{ category.name }}</text>
          <text class="task-count">{{ getTaskCount(category.id) }} 个任务</text>
        </view>
        <view class="category-actions" @click.stop>
          <text class="iconfont icon-edit" @click="editCategory(category)"></text>
          <text class="iconfont icon-trash" @click="deleteCategory(category)"></text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="categories.length === 0" class="empty-state">
        <text class="iconfont icon-category"></text>
        <text class="empty-text">暂无分类，点击右上角添加</text>
      </view>
    </view>

    <!-- 添加/编辑分类弹窗 -->
    <uni-popup ref="categoryPopup" type="bottom" :maskClick="false">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{ isEditingCategory ? '编辑分类' : '添加分类' }}</text>
          <text class="popup-close" @click="closeCategoryModal">✕</text>
        </view>

        <view class="popup-body">
          <!-- 分类名称 -->
          <view class="form-group">
            <text class="form-label">分类名称</text>
            <input 
              type="text" 
              v-model="categoryForm.name"
              placeholder="请输入分类名称" 
              class="form-input"
              maxlength="10"
              confirm-type="done"
            />
          </view>

          <!-- 分类颜色 -->
          <view class="form-group">
            <text class="form-label">选择颜色</text>
            <view class="color-options">
              <view 
                v-for="color in colorOptions" 
                :key="color"
                class="color-option"
                :class="{ active: categoryForm.color === color }"
                :style="{ backgroundColor: color }"
                @click="categoryForm.color = color"
              >
                <text v-if="categoryForm.color === color" class="iconfont icon-check"></text>
              </view>
            </view>
          </view>
        </view>

        <view class="popup-actions">
          <button class="cancel-btn" @click="closeCategoryModal">取消</button>
          <button 
            class="confirm-btn" 
            @click="saveCategory"
            :disabled="!categoryForm.name.trim()"
          >
            确认
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 分类操作弹窗 -->
    <uni-popup ref="actionsPopup" type="actionSheet">
      <view class="actions-container">
        <view class="action-item" @click="editSelectedCategory">
          <text class="iconfont icon-edit"></text>
          <text>编辑分类</text>
        </view>
        <view class="action-item delete-action" @click="deleteSelectedCategory">
          <text class="iconfont icon-trash"></text>
          <text>删除分类</text>
        </view>
        <view class="action-item cancel" @click="closeActionsModal">
          <text>取消</text>
        </view>
      </view>
    </uni-popup>

    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-mask">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import taskApi from '../../api/task';
import { showToast, confirm } from '../../utils/uni';
// 导入uni-popup组件
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';

const router = useRouter();

// 响应式数据
const categories = ref([]);
const tasks = ref([]);
const isLoading = ref(false);
const categoryPopup = ref(null);
const actionsPopup = ref(null);
const selectedCategoryId = ref('');
const currentCategory = ref(null);
const isEditingCategory = ref(false);

// 分类表单数据
const categoryForm = ref({
  id: '',
  name: '',
  color: '#4a90e2'
});

// 颜色选项
const colorOptions = [
  '#4a90e2', '#ff6b6b', '#4caf50', '#fbc02d', '#9c27b0',
  '#e91e63', '#3f51b5', '#00bcd4', '#009688', '#795548',
  '#607d8b', '#8bc34a', '#ff9800', '#7c4dff', '#ff4081'
];

// 方法
const loadCategories = async () => {
  isLoading.value = true;
  try {
    const res = await taskApi.getTaskCategories();
    categories.value = res.data || [];
  } catch (error) {
    showToast('加载分类失败', 'error');
    console.error('Failed to load categories:', error);
  } finally {
    isLoading.value = false;
  }
};

const loadTasks = async () => {
  try {
    const res = await taskApi.getTaskList({ pageSize: 100 });
    tasks.value = res.data?.list || [];
  } catch (error) {
    console.error('Failed to load tasks:', error);
  }
};

const getTaskCount = (categoryId) => {
  return tasks.value.filter(task => task.categoryId === categoryId).length;
};

const selectCategory = (categoryId) => {
  selectedCategoryId.value = categoryId;
};

const showAddCategoryModal = () => {
  isEditingCategory.value = false;
  categoryForm.value = {
    id: '',
    name: '',
    color: '#4a90e2'
  };
  categoryPopup.value?.open();
};

const editCategory = (category) => {
  currentCategory.value = category;
  editSelectedCategory();
};

const showCategoryActions = (category) => {
  currentCategory.value = category;
  selectedCategoryId.value = category.id;
  actionsPopup.value?.open();
};

const editSelectedCategory = () => {
  if (!currentCategory.value) return;
  
  isEditingCategory.value = true;
  categoryForm.value = {
    id: currentCategory.value.id,
    name: currentCategory.value.name,
    color: currentCategory.value.color
  };
  
  closeActionsModal();
  categoryPopup.value?.open();
};

const deleteCategory = (category) => {
  currentCategory.value = category;
  deleteSelectedCategory();
};

const deleteSelectedCategory = async () => {
  if (!currentCategory.value) return;
  
  closeActionsModal();
  
  // 检查是否有任务使用此分类
  const taskCount = getTaskCount(currentCategory.value.id);
  let confirmMessage = `确定要删除分类"${currentCategory.value.name}"吗？`;
  
  if (taskCount > 0) {
    confirmMessage += `\n该分类下有${taskCount}个任务，删除后任务将变为无分类状态。`;
  }
  
  const confirmed = await confirm(confirmMessage);
  
  if (!confirmed) return;
  
  isLoading.value = true;
  try {
    await taskApi.deleteTaskCategory(currentCategory.value.id);
    showToast('分类已删除');
    
    // 从列表中移除
    const index = categories.value.findIndex(c => c.id === currentCategory.value.id);
    if (index > -1) {
      categories.value.splice(index, 1);
    }
    
    // 更新任务列表（移除分类ID）
    tasks.value.forEach(task => {
      if (task.categoryId === currentCategory.value.id) {
        task.categoryId = '';
        task.category = null;
      }
    });
    
    currentCategory.value = null;
  } catch (error) {
    showToast('删除分类失败', 'error');
    console.error('Failed to delete category:', error);
  } finally {
    isLoading.value = false;
  }
};

const closeCategoryModal = () => {
  categoryPopup.value?.close();
};

const closeActionsModal = () => {
  actionsPopup.value?.close();
};

const validateCategoryForm = () => {
  const name = categoryForm.value.name.trim();
  
  if (!name) {
    showToast('请输入分类名称', 'warn');
    return false;
  }
  
  // 检查名称是否重复
  const isDuplicate = categories.value.some(c => 
    c.name === name && (!isEditingCategory.value || c.id !== categoryForm.value.id)
  );
  
  if (isDuplicate) {
    showToast('分类名称已存在', 'warn');
    return false;
  }
  
  return true;
};

const saveCategory = async () => {
  if (!validateCategoryForm()) return;
  
  isLoading.value = true;
  
  try {
    const categoryData = {
      name: categoryForm.value.name.trim(),
      color: categoryForm.value.color
    };
    
    let res;
    if (isEditingCategory.value) {
      res = await taskApi.updateTaskCategory(categoryForm.value.id, categoryData);
      showToast('分类已更新');
      
      // 更新本地列表
      const index = categories.value.findIndex(c => c.id === categoryForm.value.id);
      if (index > -1) {
        categories.value[index] = { ...categories.value[index], ...res.data };
      }
      
      // 更新相关任务的分类信息
      tasks.value.forEach(task => {
        if (task.categoryId === categoryForm.value.id) {
          task.category = { ...task.category, ...res.data };
        }
      });
    } else {
      res = await taskApi.createTaskCategory(categoryData);
      showToast('分类已创建');
      
      // 添加到本地列表
      categories.value.push(res.data);
    }
    
    closeCategoryModal();
  } catch (error) {
    showToast(isEditingCategory.value ? '更新分类失败' : '创建分类失败', 'error');
    console.error('Failed to save category:', error);
  } finally {
    isLoading.value = false;
  }
};

const onBack = () => {
  router.back();
};

// 生命周期
onMounted(() => {
  loadCategories();
  loadTasks();
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-btn .iconfont {
  font-size: 36rpx;
  color: #333;
}

.navbar .title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.add-btn {
  font-size: 32rpx;
  color: #4a90e2;
  font-weight: bold;
}

.category-list {
  padding: 20rpx;
}

.category-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  transition: all 0.3s;
  position: relative;
}

.category-item.active {
  background-color: #f0f8ff;
}

.category-color {
  width: 40rpx;
  height: 40rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.category-info {
  flex: 1;
}

.category-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.task-count {
  display: block;
  font-size: 24rpx;
  color: #999;
}

.category-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.category-actions .iconfont {
  font-size: 28rpx;
  color: #999;
}

.category-actions .icon-edit:hover {
  color: #4a90e2;
}

.category-actions .icon-trash:hover {
  color: #ff6b6b;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-state .iconfont {
  font-size: 120rpx;
  color: #ddd;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.popup-content {
  background-color: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
}

.popup-body {
  padding: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.form-input {
  width: 100%;
  padding: 20rpx;
  font-size: 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 16rpx;
  box-sizing: border-box;
}

.color-options {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20rpx;
}

.color-option {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: transform 0.2s;
}

.color-option:active {
  transform: scale(0.95);
}

.color-option.active {
  box-shadow: 0 0 0 4rpx #fff, 0 0 0 6rpx #4a90e2;
}

.color-option .iconfont {
  font-size: 36rpx;
  color: #fff;
}

.popup-actions {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.popup-actions button {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  border-radius: 40rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #4a90e2;
  color: #fff;
}

.confirm-btn:disabled {
  background-color: #ccc;
  color: #fff;
}

.actions-container {
  background-color: #fff;
  border-radius: 30rpx;
  overflow: hidden;
}

.action-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  font-size: 32rpx;
  color: #333;
  border-bottom: 2rpx solid #f0f0f0;
}

.action-item:last-child {
  border-bottom: none;
}

.action-item .iconfont {
  font-size: 36rpx;
  margin-right: 20rpx;
}

.action-item.delete-action {
  color: #ff6b6b;
}

.action-item.cancel {
  background-color: #f5f5f5;
  margin-top: 20rpx;
  border-radius: 30rpx;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 8rpx solid #f3f3f3;
  border-top: 8rpx solid #4a90e2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #fff;
  font-size: 32rpx;
}
</style>